package example.hello_security.entity;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * (User)实体类
 *
 * @author makejava
 * @since 2024-10-27 00:52:35
 */

@Data
public class LoginsUserDetail implements UserDetails {

    private User user;
    List<String> roleNames;
    List<String> permissionNames;


    public LoginsUserDetail(User user) {
        this.user = user;
    }

    /**
     * description 自定义权限
     * springSecurity的默认的Authorities中，
     * 以ROLE_开头的是角色，其余是permission权限，我们的目的是根据我们自己的roleNames和PermissionNames进行Authorities的返回，
     * 交给security的上下文,（交给上下文的位置在UserDetailService，需要重写的时候配合DAO（mysql）进行添加
     * @author zken
     * CreateDate 2024/10/28 00:02:11
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        String rolePrefix = "ROLE_";
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        roleNames.forEach(
                role -> authorities.add(new SimpleGrantedAuthority(rolePrefix + role))
        );
        permissionNames.forEach(
                permission -> authorities.add(new SimpleGrantedAuthority(permission))
        );

        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getPhone();
    }

    @Override
    public boolean isEnabled() {
        return UserDetails.super.isEnabled();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return UserDetails.super.isCredentialsNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return UserDetails.super.isAccountNonLocked();
    }

    @Override
    public boolean isAccountNonExpired() {
        return UserDetails.super.isAccountNonExpired();
    }

}

